<?php

namespace sms;

use Curl\Curl;
use extend\UserConf;
use query;

class sms_operation
{
    public $url;
    public $token;
    public $type;

    /**
     * sms_operation constructor.
     * @param $url
     * @param $token
     * @param int $type 发信类型 1验证码，2工单，3订单
     */
    public function __construct($url, $token, $type = 1)
    {
        $this->url = ($url <> href() ? href() : $url);
        $this->token = $token;
        $this->type = $type;
    }

    public function user_data_set($Mobile)
    {
        $ar = Curl::curl(false, ['act' => 12, 'Mobile' => $Mobile], true, 1, 2);
        if ($ar['code'] == 1) {
            return true;
        } else {
            dier($ar);
        }
    }

    /**
     * @param $uid
     * @param $order
     * 发送订单提醒短信！
     */
    public function user_order_tips($uid, $order)
    {
        global $DB;
        $UID = $DB->get_row("SELECT mobile FROM `sky_user` WHERE `id` = '$uid' AND `state` = 1 LIMIT 1");
        if (!$UID || $UID['mobile'] == '') return false;
        $order = $DB->get_row("SELECT id FROM `sky_order` WHERE `order` = '$order' ");
        if (!$order) return false;
        $arr_post = [
            'act' => 'send',
            'code' => $order['id'],
            'mobile' => $UID['mobile'],
            'type' => $this->type,
        ];
        Curl::curl(false, $arr_post, true, '/SMS/index', 2);
        return true;
    }

    public function user_data()
    {
        dier(Curl::curl(false, ['act' => 11], true, 1, 2));
    }

    /**
     * @param string $mobile 手机号
     * @param int $num 每日验证次数
     * 发送登陆验证码
     */
    public function user_login($mobile = '', $num = 3)
    {
        global $accredit, $DB, $times, $date, $conf;

        if ($conf['sms_switch_user'] <> 1) dies(-1, '当前站点未开启短信登陆/注册方式,可使用下方QQ互联登陆/注册！');

        $IP = userip();

        $sms = new sms_operation(href(), $accredit['token'], 1);
        if ($mobile == '') dies(-1, '请将手机号填写完整！');
        $count = $DB->count("SELECT count(*) FROM `sky_journal` WHERE `name` = '短信验证' AND `date` > '$times' AND `ip` = '{$IP}' "); //今日发信次数
        if ($count >= $num) dies(-1, '今日短信登陆次数已经耗尽<br>每日只可发送' . $num . '次短信验证码登陆！');
        $_SESSION['VerifyCodeLogin'] = $sms->randString();
        $_SESSION['MobileLogin'] = $mobile;
        $arr = $sms->sum_send($_SESSION['VerifyCodeLogin'], $_SESSION['MobileLogin']);
        if ($arr['code'] == 1) {
            userlog('短信验证', $IP, '-1');
            dier($arr);
        } else dier($arr);
    }

    /**
     * 产生随机数串
     * @param integer $len 随机数字长度
     * @return string
     */
    public function randString($len = 6)
    {
        $chars = str_repeat('0123456789', 3);
        $chars = str_repeat($chars, $len);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }

    /**
     * @param string $code 短信内容
     * @param string $Moblie 收信电话
     * 短信发送类
     */
    public function sum_send($code = '', $Moblie = '')
    {
        $arr_post = [
            'act' => 'send',
            'code' => $code,
            'mobile' => $Moblie,
            'type' => $this->type,
        ];
        return Curl::curl(false, $arr_post, true, '/SMS/index', 2);
    }

    /**
     * @param string $code
     * 用户后台短信验证登陆
     */
    public function user_login_verify($code = '')
    {
        global $DB, $date, $conf;
        if (empty($_SESSION['VerifyCodeLogin']) || empty($_SESSION['MobileLogin'])) dies(-2, '请先发送验证码！');
        if ($code == '') dies(-1, '请填写完整！');
        if ((int)$_SESSION['VerifyCodeLogin'] <> $code) dies(-1, '验证码有误,请核对后再输入！');
        $reu = $DB->get_row("SELECT * FROM `sky_user` WHERE `mobile` = '{$_SESSION['MobileLogin']}' LIMIT 1 ");
        if ($reu) {
            userlog('后台登陆', '用户于' . $date . '通过手机号成功登陆后台！', $reu['id'], '0');
            setcookie("THEKEY", $reu['user_idu'], time() + 3600 * 12 * 15, '/');
            query::OrderUser($reu['id']);
            dies(1, '短信验证通过,点击确定进入后台！');
        } else { //注册
            $uid_md = md5($_SESSION['MobileLogin']);
            $IP = userip();
            $Uty = UserConf::judge();
            if ($Uty == false) {
                $Uty = 0;
            } else $Uty = $Uty['id'];
            if (empty($_COOKIE['INVITED_STATUS'])) {
                $b = $DB->query("INSERT INTO `sky_user` (`mobile`,`grade`,`user_idu`, `superior`,`currency`, `ip`,`image`,`name`,`state`,`recent_time`, `found_date`) 
VALUES ('{$_SESSION['MobileLogin']}','{$conf['userdefaultgrade']}','$uid_md', '$Uty', '0', '$IP', '{$conf['logo']}' , '平台用户' ,  '1', '$date', '$date');");
            } else {
                $c = $DB->get_row("SELECT * FROM `sky_user` WHERE `id` = '{$_COOKIE['INVITED_STATUS']}' LIMIT 1");
                if ($c) {
                    $GETTE = 1;
                    $b = $DB->query("INSERT INTO `sky_user` (`mobile`,`grade`,`user_idu`, `superior`,`currency`, `ip`,`image`,`name`,`state`,`recent_time`, `found_date`)
 VALUES ('{$_SESSION['MobileLogin']}','{$conf['userdefaultgrade']}','$uid_md', '{$_COOKIE['INVITED_STATUS']}', '0', '$IP', '{$conf['logo']}' , '平台用户' ,  '1', '$date', '$date');");
                } else {
                    setcookie("INVITED_STATUS", null, time() - 3600 * 12 * 15, '/'); #删无效邀请用户
                    $b = $DB->query("INSERT INTO `sky_user` (`mobile`,`grade`,`user_idu`, `superior`,`currency`, `ip`,`image`,`name`,`state`,`recent_time`, `found_date`) 
VALUES ('{$_SESSION['MobileLogin']}','{$conf['userdefaultgrade']}','$uid_md', '$Uty', '0', '$IP', '{$conf['logo']}' , '平台用户' ,  '1', '$date', '$date');");
                }
            }

            if ($b) {
                $GETID = $DB->get_row("SELECT * FROM `sky_user` WHERE `mobile` = '{$_SESSION['MobileLogin']}' AND state = 1  LIMIT 1");
                if ($GETTE == 1) {
                    /**
                     * 写入邀请奖励！
                     */
                    $FTR = $DB->get_row("SELECT * FROM `sky_invite` WHERE `ip` = '$IP'  LIMIT 1"); #邀请列表内
                    if (!$FTR) { #如果IP已经存在,则无法奖励
                        $award = $conf['award']; #奖励点
                        userlog('邀请奖励', '恭喜您成功邀请到用户[' . $GETID['name'] . ']特奖励您' . $award . $conf['currency'] . '！,再接再厉哦', $_COOKIE['INVITED_STATUS'], $award);
                        @$DB->query("INSERT INTO `sky_invite` (`uid`, `invitee`, `award`, `ip`, `creation_time`) VALUES ('{$_COOKIE['INVITED_STATUS']}', '{$GETID['id']}', '$award', '$IP', '$date')");
                    } else {
                        userlog('失败邀请', '系统判断您的邀请对象：[' . $GETID['name'] . ']已经在其他账号接收过邀请,无法奖励！,请邀请真实用户！', $_COOKIE['INVITED_STATUS'], 0);
                    }
                }
                if ($GETID) query::OrderUser($GETID['id']);
                include_once(SYSTEM_ROOT . "extend/GoodsCart.php");
                if ($GETID) \extend\GoodsCart::UserCookieDer($GETID['id']);

                setcookie("THEKEY", $uid_md, time() + 3600 * 12 * 15, '/');
                dies(1, '短信验证通过,点击确定进入后台<br>检测到您是第一次登陆本站<br>进入后台后可点击QQ互联绑定QQ<br>即可使用QQ快捷登陆本站！');
            } else { #登陆失败
                dies(1, '平台账号创建失败,无法完成登陆,请使用下方QQ登陆！');
            }
        }
    }

    /**
     * @param string $mobile 手机号
     * 发送短信验证码
     */

    public function admin_login($mobile = '')
    {
        return Curl::curl(false, ['act' => 13, 'mobile' => $mobile, 'type' => $this->type], true, 1, 2);
    }

    /**
     * @param string $code 验证码
     * 根据验证码操作
     */
    public function admin_login_verify($code = '')
    {
        global $DB, $date;
        $ar = Curl::curl(false, ['act' => 14, 'code' => $code], true, 1, 2);
        if ($ar['code'] >= 0) {
            $IP = IP_user();
            @$DB->query("INSERT INTO `sky_login` (`token`,`ip`,`state`,`finish_time`, `date_created`)  VALUES ( '{$ar['token']}', '$IP','1','$date','$date');");
            setcookie("ADMIN_TOKEN", $ar['token'], time() + 3600 * 12 * 15, '/');
            return ['code' => 1, 'msg' => $ar['msg']];
        } else return $ar;
    }

    public static function WeixOrder($order, $name)
    {
        global $DB, $conf;
        if ($conf['weix_notice'] == '-1') return false;
        $re = $DB->get_row("SELECT * FROM `sky_order` WHERE `order` = '$order' LIMIT 1");
        if (!$re) return false;
        if ($re) {
            $data = [
                'act' => 15,
                'order' => $order,
                'price' => $re['price'],
                'return' => ($re['return'] == '' ? '未知下单返回' : $re['return']),
                'uid' => $re['uid'],
                'date' => $re['addtitm'],
                'balance' => $re['user_rmb'],
                'state' => $re['state'],
                'money' => $re['money'],
                'name' => $name,
                'payment' => $re['payment'],
            ];
            Curl::curl(false, $data, true, 1, 2);
            return true;
        } else return false;
    }
}

?>